package com.ztil.socket;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SocketHandler {

	private Map<String, Socket> _sockets;
	private ExecutorService _pool;

	public SocketHandler() {
		this._sockets = new HashMap<>();
		this._pool = Executors.newCachedThreadPool();
	}

	public void hand(Socket socket) {
		_sockets.put(socket.getRemoteSocketAddress().toString(), socket);
	}

	public void read() {
		for (Entry<String, Socket> socket : _sockets.entrySet()) {
			Socket rcvSocket = socket.getValue();
			boolean isConnection = rcvSocket.isConnected() && !rcvSocket.isClosed();
			if (isConnection) {
				_pool.execute(new Read(rcvSocket));
			} else {
				_sockets.remove(rcvSocket.getRemoteSocketAddress());
			}
		}
	}

	public void write(String msg) {
		PrintWriter pw;
		for (Entry<String, Socket> socket : _sockets.entrySet()) {
			Socket rcvSocket = socket.getValue();
			boolean isConnection = rcvSocket.isConnected() && !rcvSocket.isClosed();
			if (isConnection) {
				try {
					pw = new PrintWriter(rcvSocket.getOutputStream());
					pw.println(msg);
					pw.flush();
				} catch (IOException e) {
					e.printStackTrace();
				}
			} else {
				_sockets.remove(rcvSocket.getRemoteSocketAddress());
			}
		}
	}

}